<?php
class Merchant_Service_Orders
{
	public static $orderStatusCn =array(
	    0 => '删除',
	    1 => '草稿',
        2 => '已确认',
        3 => '缺货', 	//缺货
        4 => '待发货', 		//待发货
        5 => '已发货',			//已发货
        6 => '已完成',		//已完成
	);
	public static $operationArrCn =array(
	    0 => array(1 => '转 草稿'),
	    1 => array(0 => '转 删除', 2 => '确认'),
        2 => array(0 => '转 删除', 1 => '转 草稿', 3 => '确认'),
        3 => array(0 => '转 删除', 1 => '转 草稿'),
        4 => array(0 => '转 删除', 1 => '转 草稿', 3 => '确认'),
	);
	public static $abnormalTextCn =array(
		0 => '无异常',
	    1 => '库存不足',//库存不足
        2 => '余额不足', //余额不足
        3=> '截单'
	);

    public static $orderStatus =array(
        0 => 'Delete',
        1 => 'Draft',
        2 => 'Confirm',
        3 => 'Abnormal', 	//缺货
        4 => 'Processing', 		//待发货
        5 => 'Shipped',			//已发货
        6 => 'Delivered',		//已完成
    );
    public static $operationArr =array(
        0 => array(1 => 'To draft'),
        1 => array(0 => 'To delete', 2 => 'Confirm'),
        2 => array(0 => 'To delete', 1 => 'To draft', 3 => 'Submit'),
        3 => array(0 => 'To delete', 1 => 'To draft'),
        4 => array(0 => 'To delete', 1 => 'To draft', 3 => 'Submit'),
    );
    public static $abnormalText =array(
        0 => '--',
        1 => 'Out of stock',//库存不足
        2 => 'Insufficient funds', //余额不足
        3=> 'stop order'
    );


    public static function add($row){
        $Obj = new Merchant_Model_Orders();
        return $Obj->add($row);
	}

	public static function update($row,$value,$field='order_id'){
        $Obj = new Merchant_Model_Orders();
        return $Obj->update($row,$value,$field);
	}

	public  function changeStatus($orderCode,$status,$unCheckPlan = false,$feeEnforce=0){
		$process = new Merchant_Service_OrderProccess($orderCode);
		$result = $process->submited($orderCode,$status,$unCheckPlan,$feeEnforce);
		return $result;
	}
	
	public  static function stop($orderCode,$customerId=null){
		$result=array('ask'=>'Error','message'=>'Internal Error !.');
		//判断所有不符合的状态
		$checkorder=Merchant_Service_Orders::getByValue($orderCode,'orders_code');
		if($checkorder){
			$process = new Merchant_Service_OrderProccess($orderCode);
			if(!empty($customerId)){
				$process->setCustomer($customerId);
			}
			$resultStop = $process->stop();
			if($resultStop['ask']=='Error'){
				$result['ask']='Error';
				$result['message']=$resultStop['msg'];
				return $result;
			}
			return array('ask'=>$resultStop['ask'],'message'=>$resultStop['msg']);
		}else{
			return array('ask'=>'Error','message'=>'Order code can not be null.');
		}
	}
	
	public static function delete($value,$field='st_id'){
        $Obj = new Merchant_Model_Orders();
        return $Obj->delete($value,$field);

	}


	public static function getByValue($value,$field='order_id'){
        $Obj = new Merchant_Model_Orders();
        return $Obj->getByValue($value,$field);
	}

    public static function getByCondition($condition,$type='*',$orderby="",$page=0,$pageSize=0,$isDetail=true){
        $Obj = new Merchant_Model_Orders();
        $result = $Obj->getByCondition($condition,$type,$orderby,$page,$pageSize);
        if(is_array($result)&$isDetail){
        	$statusArr = self::$orderStatus;
        	$abnormalTextArr = self::$abnormalText;
        	foreach ($result as $key =>$val){
        		$countryInfo = Default_Service_Country::getByValue($val['consignee_country_id'],'country_id');
        		$customerInfo = Merchant_Service_Customer::get();
        		$warehouseInfo = Default_Service_Warehouse::getById($val['warehouse_id']);
        		$result[$key]['warehouse_name'] = $warehouseInfo['warehouse_name'];
        		$result[$key]['consignee_country'] = $countryInfo['country_code'];
        		$result[$key]['customer'] = $customerInfo['customer_id'];
        		$result[$key]['orders_status_str'] = $statusArr[$val['orders_status']];
				$result[$key]['products'] = self::getOrderProducts($val['orders_code']);
				$result[$key]['abnormalText'] = $abnormalTextArr[$val['underreview_status']];
        	}
        }
        return $result;
	}

	public static function getOrderProducts($orderCode){
		$orderProductModel = new Merchant_Model_OrderProduct();
		$orderProducts = $orderProductModel->getByCondition(array("orders_code" => $orderCode));
		$orderProductInfos = array();
		if(is_array($orderProducts)){
			$productService = new Merchant_Service_Product();
			foreach($orderProducts as $key => $value){
				$orderProductInfo = $productService->getProductInfo($value['product_id']);
				$orderProductInfo['quantity'] = $value['op_quantity'];
				$orderProductInfos[] = $orderProductInfo;
			}
		}
		return $orderProductInfos;
	}
    public static function getStatusList() {
        return array(
            '0' =>'不可用',
            '1' =>'可用',
        );
    }

    public static function validator($val) {
        return Merchant_Service_FactoryValidate::factoryMethod($val);
    }

	
	/**
	* 读取上传文件
	* @param string $fileName
	* @return array
	*/
	public function readUploadFile($fileName, $filePath) {
		$productObj = Merchant_Service_Product::getInstance();
		
		$loginInfo = $productObj->getLoginInfo();	// 获取用户登录信息
		$res = array();
		$res['error'] = $res['data'] = array();

		$pathinfo = pathinfo($fileName);
		$fileData = $orderArr = array ();
        if(isset($pathinfo["extension"]) && $pathinfo["extension"] == "xls"){
        	$fileData = Merchant_Service_Upload :: readEXCEL($filePath,0);
        }elseif (isset($pathinfo["extension"]) && $pathinfo["extension"] == "csv") {
        	$fileData = Merchant_Service_Upload :: readCSV($filePath);
        }else{
            $res['error'][] = 'Unit file format error.';
            return $res;
        }
		
		$pointKey = 0;
		foreach ($fileData as $key => $val) {			
			//将第一行value转成其他行的key
			if ($key == 0) {
				continue;
			}
			if($key == 1 && $val[0]==''){
				$res['error'][] = 'The first line reference number can\'t be empty.';
				return $res;
			}					
			
			if(isset($val[0]) && $val[0]){
				$val[14] = (int) $val[14];	//把数量转换为整数
				//国家信息
				$country_code = substr($val[2],0,2);
				$countryInfo = Default_Service_Country::getByValue($country_code,'country_code');
				
				$pointKey = $key;
				$orderArr[$key]['customer_order_code'] = $val[0];	// ReferenceNo
				$orderArr[$key]['shipping_method'] = $val[1];
				$orderArr[$key]['country'] = $val[2];
				$countryInfo['country_id'] && $orderArr[$key]['consignee_country_id'] = $countryInfo['country_id'];
				$orderArr[$key]['consignee_first_name'] = $val[3];
				$orderArr[$key]['consignee_last_name'] = $val[4];
				
				$orderArr[$key]['consignee_address1'] = $val[5];
				if(!$val[6]){ $val[6] = ''; }
				$orderArr[$key]['consignee_address2'] = $val[6];	//  address2为非必填
				$orderArr[$key]['consignee_city'] = $val[7];
				$orderArr[$key]['consignee_region'] = $val[8];		//State/Provice
				$orderArr[$key]['consignee_zip'] = $val[9];			//Postalcode
				
				if(!$val[10]){
					$val[10] = $loginInfo->customer['customer_email'];
				}
				$orderArr[$key]['email'] = $val[10];		//  email为非必填
				$orderArr[$key]['company'] = $val[11];
				$orderArr[$key]['consignee_phone'] = $val[12];		//PhoneNo
				$orderArr[$key]['order_product'][$key]['product_sku'] = $val[13];		//产品SKU		
				$orderArr[$key]['order_product'][$key]['op_quantity']  = $val[14];	//产品数量
				$orderArr[$key]['order_product'][$key]['op_description'] = $val[15];
				
				//预定义产品信息，防止报错
				$orderArr[$key]['order_product'][$key]['product_id'] = '';	
				$orderArr[$key]['order_product'][$key]['product_title'] = '';	//SKU 产品名称
				$orderArr[$key]['order_product'][$key]['category'] = '';		//类别
				$orderArr[$key]['order_product'][$key]['op_declared_value'] = 0;
				$orderArr[$key]['order_product'][$key]['op_unit_price'] = 0;
				$orderArr[$key]['order_product'][$key]['op_weight'] = 0;
				$orderArr[$key]['parcel_declared_value'] = 0;				
				
				//产品信息
				$productInfo = $productObj->getProductBySku($val[13],$loginInfo->customer["customer_id"]);
				if($productInfo){
					$orderArr[$key]['order_product'][$key]['product_id'] = $productInfo['product_id'];	
					$orderArr[$key]['order_product'][$key]['product_title'] = $productInfo['product_title'];
					$orderArr[$key]['order_product'][$key]['category'] = $productInfo['category']['poc_value'];	//类别
					$orderArr[$key]['order_product'][$key]['op_declared_value'] = $productInfo['product_declared_value'];
					$orderArr[$key]['order_product'][$key]['op_unit_price'] = $productInfo['product_declared_value'];
					$orderArr[$key]['order_product'][$key]['op_weight'] = $productInfo['product_weight'];
					$orderArr[$key]['parcel_declared_value'] = $productInfo['product_declared_value']*$val[14];
				}
				
				//以下产品信息暂不明确
				$orderArr[$pointKey]['order_product'][$key]['op_ref_tnx'] = '';
				$orderArr[$pointKey]['order_product'][$key]['op_ref_item_id'] = '';
				$orderArr[$pointKey]['order_product'][$key]['op_ref_paydate'] = '';
				
				//以下不是由excel表格提交的
				$orderArr[$key]['customer_id'] = $loginInfo->customer["customer_id"];
				$orderArr[$key]['consignee_company'] = $loginInfo->customer["customer_company_name"];
				$orderArr[$key]['consignee_email'] = $loginInfo->customer["customer_email"];
				$orderArr[$key]['parcel_contents'] = '';
				
				$orderArr[$key]['parcel_quantity'] = $val[14];	//内件数量 (只有一件产品时)
				$orderArr[$key]['remark'] = '';
				$orderArr[$key]['shipping_fee_estimate'] = '';		
				$orderArr[$key]['order_id'] = '';
				$orderArr[$key]['regAccount'] = '';			//暂时不知道做什么的
				
			}elseif (!$val[0] && $val[13] && $val[14]){
				//预定义产品信息，防止报错
				$orderArr[$pointKey]['order_product'][$key]['product_id'] = '';				
				$orderArr[$pointKey]['order_product'][$key]['op_declared_value'] = 0;
				$orderArr[$pointKey]['order_product'][$key]['op_unit_price'] = 0;
				$orderArr[$pointKey]['order_product'][$key]['op_weight'] = 0;
				$orderArr[$pointKey]['order_product'][$key]['product_title'] = '';	//SKU 产品名称
				$orderArr[$pointKey]['order_product'][$key]['category'] = '';		//类别
				
				$productInfo = $productObj->getProductBySku($val[13],$loginInfo->customer["customer_id"]);
				if($productInfo){
					//产品信息
					$orderArr[$pointKey]['order_product'][$key]['product_id'] = $productInfo['product_id'];	
					$orderArr[$pointKey]['order_product'][$key]['product_title'] = $productInfo['product_title'];
					$orderArr[$pointKey]['order_product'][$key]['category'] = $productInfo['category']['poc_value'];	//类别
								
					$orderArr[$pointKey]['order_product'][$key]['op_declared_value'] = $productInfo['product_declared_value'];
					$orderArr[$pointKey]['order_product'][$key]['op_unit_price'] = $productInfo['product_declared_value'];
					$orderArr[$pointKey]['order_product'][$key]['op_weight'] = $productInfo['product_weight'];
					$orderArr[$pointKey]['parcel_declared_value'] += $productInfo['product_declared_value']*$val[14];
				}
				
				$orderArr[$pointKey]['order_product'][$key]['product_sku'] = $val[13];		//产品SKU		
				$orderArr[$pointKey]['order_product'][$key]['op_quantity']  = $val[14];	//产品数量
				$orderArr[$pointKey]['order_product'][$key]['op_description'] = $val[15];
				$orderArr[$pointKey]['parcel_quantity'] += $val[14];		//内件数量 多个产品时
							
				//以下产品信息暂不明确
				$orderArr[$pointKey]['order_product'][$key]['op_ref_tnx'] = '';
				$orderArr[$pointKey]['order_product'][$key]['op_ref_item_id'] = '';
				$orderArr[$pointKey]['order_product'][$key]['op_ref_paydate'] = '';
			}
		}
		$res['data'] = $orderArr;		
		return $res;
	}
	
	/**
	 * 批量检查 上传的数据
	 * $orderInfo 必须为数组，上传的多个订单数据
	 * 返回原数组及错误信息
	 */
	public function uploadDataValidator($orderArr) {
		$productObj = Merchant_Service_Product::getInstance();
		foreach ($orderArr as $key => $orderInfo){
			$orderArr[$key]['error_arr'] = array();
			$error = self::validator($orderInfo);
			if($error){
				$orderArr[$key]['has_error'] = 1;	//当前数据行 存在错误
				$orderArr[$key]['error_arr'] = $error;
			}else{				
				$orderArr[$key]['has_error'] = 0;
				$orderArr[$key]['error_arr'] = '';
			}
			
			if(isset($orderInfo['order_product']) && $orderInfo['order_product']){
				foreach ($orderInfo['order_product'] as $key2 => $val2){
					if(!$val2){
						unset($orderInfo['order_product'][$key2]);
						continue;
					}
					$productInfo = $productObj->getProductBySku($val2['product_sku'],$orderInfo['customer_id']);
					if(!$productInfo){
						$orderArr[$key]['has_error'] = 1;
						$orderArr[$key]['error_arr'][] = 'SKU'.$val2['product_sku'].' does not exist.';
					}
					if(!$val2['op_quantity'] || $val2['op_quantity']<0 ){
						$orderArr[$key]['has_error'] = 1;
						$orderArr[$key]['error_arr'][] = 'Product quantity must be positive integer.';
					}					
				}
				if(count($orderInfo['order_product'])==0){
					$orderArr[$key]['has_error'] = 1;
					$orderArr[$key]['error_arr'][] = 'Product SKU and quantity can\'t be empty.';
				}

			}else{
				$orderArr[$key]['has_error'] = 1;
				$orderArr[$key]['error_arr'][] = 'Product SKU and quantity can\'t be empty.';
			}
			
		}
		
		return $orderArr;
	}
	
	/**
	 * 检查用户订单号是否正确
	 * @param $ordersCode
	 */
	public static function checkCustomerOrder($ordersCode) {
		$error='';
		$customerService = new Merchant_Service_Customer();
		$customerInfo = $customerService->getLoginInfo()->customer;
		$customer_id = $customerInfo['customer_id'];
		
		if(!$ordersCode){
			$error = 'Order No can not be empty!.';
		}else {
			$cond = array('orders_code'=>$ordersCode,'customer_id'=>$customer_id);
			$orderInfo = Merchant_Service_Orders::getByCondition($cond);
			if(!$orderInfo){
				$error = 'This order code is not correct.';		
			}
		}
		return $error;
	}
	

}
?>